package com.example.flow.flow;


import com.example.flow.flow.model.*;
import com.example.flow.utils.GsonUtil;

import java.util.List;
import java.util.ListIterator;

/**
 * @author tangaq
 * 2023/6/13
 */
public class ModelParser {

    public static ProcessModel parse(FlowNodes flowNodes) {
        ProcessModel processModel = new ProcessModel();
        StartModel start = flowNodes.getStart();
        EndModel end = flowNodes.getEnd();

        List<TaskModel> tasks = flowNodes.getTasks();
        TransitionModel tm;
        NodeModel pre = null;
        ListIterator<TaskModel> listIterator = tasks.listIterator();
        while (listIterator.hasNext()) {
            TaskModel current = listIterator.next();
            // 首节点
            tm = new TransitionModel(current);
            if (pre == null) {
                start.setNextNode(tm);
                processModel.getNodes().add(start);
            } else {
                pre.setNextNode(tm);
            }
            processModel.getNodes().add(current);
            pre = current;
            // 尾节点
            if (!listIterator.hasNext()) {
                tm = new TransitionModel(end);
                current.setNextNode(tm);
            }
        }

        processModel.getNodes().add(end);
        return processModel;
    }


    public static void main(String[] args) {
        String json = "{\"start\":{\"name\":\"start\"},\"tasks\":[{\"name\":\"节点1\",\"preInterceptors\":\"com.demo.Before\",\"postInterceptors\":\"com.demo.After\",\"allowStop\":\"0\",\"approverType\":\"1\",\"approver\":\"\"}],\"end\":{\"name\":\"end\"}}";
        String json2 = "{\"start\":{\"name\":\"start\"},\"tasks\":[{\"name\":\"节点1\",\"preInterceptors\":\"com.demo.Before\",\"postInterceptors\":\"com.demo.After\",\"allowStop\":\"0\",\"approverType\":\"1\",\"approver\":\"111\"},{\"name\":\"节点2\",\"preInterceptors\":\"com.demo.Before\",\"postInterceptors\":\"com.demo.After\",\"allowStop\":\"0\",\"approverType\":\"1\",\"approver\":\"222\"},{\"name\":\"节点3\",\"preInterceptors\":\"com.demo.Before\",\"postInterceptors\":\"com.demo.After\",\"allowStop\":\"0\",\"approverType\":\"1\",\"approver\":\"333\"}],\"end\":{\"name\":\"end\"}}";
        FlowNodes flowNodes = GsonUtil.json2Obj(json2, FlowNodes.class);
        ProcessModel parse = ModelParser.parse(flowNodes);
        System.out.println();
    }
}
